package com.ideawedo.orm;

import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
* @author	李小布
* @email	397554852@qq.com
* @version	创建时间：2018年11月26日 下午1:23:45
*/
public class MyORMBase {
	
	private String tableName;
	
	public MyORMBase(String tableName) {
		this.tableName = tableName;
	}
	
	public void CoutData() {
		Field[] fields = this.getClass().getFields();
		for(Field f : fields){
			System.out.println(f.getType());
		}
	}
	
	/**
	 * 插入数据
	 * @return long型 主键
	 * @throws SQLException 
	 */
	public long InsertData() throws SQLException {
		long sql_key = -1;
		String sql = GetInsertSql();
		Field[] fields = this.getClass().getFields();
		Connection conn = MyORMManager.GetConnect();
    	PreparedStatement pstmt = null;
    	try{
    		pstmt = (PreparedStatement) conn.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS);
    		for(int i = 0; i < fields.length; i++){
    			switch (fields[i].getType().toString()) {
				case "byte":
					pstmt.setByte(i+1, fields[i].getByte(this));
					break;
				case "short":
					pstmt.setShort(i+1, fields[i].getShort(this));
					break;
				case "int":
					pstmt.setInt(i+1, fields[i].getInt(this));
					break;
				case "long":
					pstmt.setLong(i+1, fields[i].getLong(this));
					break;
				case "float":
					pstmt.setFloat(i+1, fields[i].getFloat(this));
					break;
				case "double":
					pstmt.setDouble(i+1, fields[i].getDouble(this));
					break;
				case "boolean":
					pstmt.setBoolean(i+1, fields[i].getBoolean(this));
					break;
				case "class java.lang.String":
					pstmt.setString(i+1, fields[i].get(this).toString());
					break;
				}
    		}
            pstmt.executeUpdate();
            ResultSet rs = pstmt.getGeneratedKeys(); 
            while (rs.next()) {
            	sql_key = rs.getInt(1);
            	break;
			}
    	}
        catch(Exception e){
        	e.printStackTrace();
        }finally {
			pstmt.close();
	        conn.commit();
	        conn.close();
        }
        return sql_key;
	}
	
	/**
	 * 获取插入语句
	 * @return
	 */
	private String GetInsertSql() {
		String sql = "insert into " + tableName + " (";
		if(MyORMManager.JudgeInsertMap(this.getClass().getName())) {
			sql = MyORMManager.GetInsertSql(this.getClass().getName());
		}
		else{
			String temp = " value(";
			Field[] fields = this.getClass().getFields();
			for(Field f : fields){
				sql += f.getName() + ",";
				temp += "?,";
			}
			sql = sql.substring(0, sql.length() - 1);
			temp = temp.substring(0, temp.length() - 1);
			sql = sql + ")" + temp + ")";
			MyORMManager.AddInsertMap(this.getClass().getName(), sql);
		}
		return sql;
	}
	
	/**
	 * 删除数据
	 * @param condition 判断条件 例:uid=xxx&uname=xxx
	 * @return 操作状态
	 * @throws SQLException 
	 */
	public boolean DeleteData(String condition) throws SQLException{
		boolean isSuccess = false;
		String sql = "delete from " + tableName + " where " + condition;
		Connection conn = MyORMManager.GetConnect();
		PreparedStatement pstmt = null;
		try {
			pstmt = (PreparedStatement) conn.prepareStatement(sql);
	        pstmt.executeUpdate();
	        isSuccess = true;
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			pstmt.close();
	    	conn.commit();
	    	conn.close();
		}
		return isSuccess;
	}
	
	/**
	 * 更新数据
	 * @param condition
	 * @return 操作状态
	 * @throws SQLException 
	 */
	public boolean UpdateData(String condition) throws SQLException {
		boolean isSuccess = false;
		String sql = GetUpdateSql() + condition;
		Connection conn = MyORMManager.GetConnect();
		Field[] fields = this.getClass().getFields();
    	PreparedStatement pstmt = null;
    	try {
    		pstmt = (PreparedStatement) conn.prepareStatement(sql);
    		for(int i = 0; i < fields.length; i++){
    			switch (fields[i].getType().toString()) {
				case "byte":
					pstmt.setByte(i+1, fields[i].getByte(this));
					break;
				case "short":
					pstmt.setShort(i+1, fields[i].getShort(this));
					break;
				case "int":
					pstmt.setInt(i+1, fields[i].getInt(this));
					break;
				case "long":
					pstmt.setLong(i+1, fields[i].getLong(this));
					break;
				case "float":
					pstmt.setFloat(i+1, fields[i].getFloat(this));
					break;
				case "double":
					pstmt.setDouble(i+1, fields[i].getDouble(this));
					break;
				case "boolean":
					pstmt.setBoolean(i+1, fields[i].getBoolean(this));
					break;
				case "class java.lang.String":
					pstmt.setString(i+1, fields[i].get(this).toString());
					break;
				}
    		}
	        pstmt.executeUpdate();
	        isSuccess = true;
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
	    	pstmt.close();
	    	conn.commit();
	    	conn.close();
		}
		return isSuccess;
	}
	
	/**
	 * 获取更新语句
	 * @param condition
	 * @return
	 */
	private String GetUpdateSql() {
		String sql = "update " + tableName + " set ";
		if(MyORMManager.JudgeUpdateMap(this.getClass().getName())) {
			sql = MyORMManager.GetUpdateSql(this.getClass().getName());
		}else {
			Field[] fields = this.getClass().getFields();
			for(Field f : fields){
				sql += f.getName() + "=?,";
			}
			sql = sql.substring(0, sql.length() - 1) + " where ";
			MyORMManager.AddUpdateMap(this.getClass().getName(), sql);
		}
		return sql;
	}
	
	/**
	 * 查询数据
	 * @param condition 查询条件
	 * @return 操作状态 成功/失败
	 * @throws SQLException 
	 */
	public boolean QueryData(String condition) throws SQLException {
		boolean isSuccess = false;
		String sql = GetQuerySql() + condition;
		Connection conn = MyORMManager.GetConnect();
		Field[] fields = this.getClass().getFields();
		PreparedStatement ptmt = null;
		try {
			ptmt = conn.prepareStatement(sql);
	        ResultSet rs = ptmt.executeQuery();
	        while (rs.next()) {
	        	for(int i = 0; i < fields.length; i++){
	    			switch (fields[i].getType().toString()) {
					case "byte":
						fields[i].setByte(this,rs.getByte(fields[i].getName()));
						break;
					case "short":
						fields[i].setShort(this,rs.getShort(fields[i].getName()));
						break;
					case "int":
						fields[i].setInt(this,rs.getInt(fields[i].getName()));
						break;
					case "long":
						fields[i].setLong(this,rs.getLong(fields[i].getName()));
						break;
					case "float":
						fields[i].setFloat(this,rs.getFloat(fields[i].getName()));
						break;
					case "double":
						fields[i].setDouble(this,rs.getDouble(fields[i].getName()));
						break;
					case "boolean":
						fields[i].setBoolean(this,rs.getBoolean(fields[i].getName()));
						break;
					case "class java.lang.String":
						fields[i].set(this,rs.getString(fields[i].getName()));
						break;
					}
	    		}
	        }
	        rs.close();
		} catch (Exception e) {
			
			e.printStackTrace();
		} finally {
			ptmt.close();
	    	conn.commit();
	    	conn.close();
		}
		return isSuccess;
	}
	
	/**
	 * 获取查询语句
	 * @return sql语句
	 */
	private String GetQuerySql() {
		String sql = "SELECT ";
		if(MyORMManager.JudgeQueryMap(this.getClass().getName())) {
			sql = MyORMManager.GetQuerySql(this.getClass().getName());
		}else {
			Field[] fields = this.getClass().getFields();
			for(Field f : fields){
				sql += f.getName() + ",";
			}
			sql = sql.substring(0, sql.length() - 1) + " from " + tableName + " where ";
			MyORMManager.AddQueryMap(this.getClass().getName(), sql);
		}
		return sql;
	}
}
